import 'dart:async';
import 'dart:io';
import 'dart:ui' as prefix0;

import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:path_provider/path_provider.dart';
import 'package:rms_mobile_client/Bloc/Storage/IDataContext.dart';
import 'package:rms_mobile_client/Entities/User.dart';
import 'package:rms_mobile_client/Localizations/Localization.dart';
import 'package:rms_mobile_client/StateManagement/ModelProvider.dart';
import 'package:rms_mobile_client/UI/Lib/Dialog.dart';
import 'package:rms_mobile_client/UI/Pages/MainPage.dart';

class SignInPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _SignInPage();
  }
}

class _SignInPage extends State<SignInPage> {
  TextEditingController _userName = TextEditingController();
  TextEditingController _userPassword = TextEditingController();

  @override
  void initState() {
    Timer(Duration(seconds: 1), (){
      var dataContext = ModelContainer.of<IDataContext>(context).model;
      if (!dataContext.users.isEmpty) return;

      Widget dialog = CupertinoAlertDialog(
        title: Text("ھىساباتىڭىزنى قۇرۇڭ"),
        content: Text("ھىسابات نامىڭىز ۋە پارولىڭىزنى كىرگۈزۈپ 'كىرىش' كونۇپكىسىنى بىسىپ تۇنجى قىتىملىق ئىشلەتكۈچى ھىساباتى قوشۇڭ."),
        actions: <Widget>[
          CupertinoButton(
            child: Text("بىلدىم"),
            onPressed: (){
              Navigator.of(context).pop();
            },
          )
        ],
      );
      dialog = Directionality(
        textDirection: TextDirection.rtl,
        child: dialog,
      );
      showCupertinoDialog(context: context, builder: (context) => dialog);
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    var lang = Localization.of(context).language;
    return Directionality(
      textDirection: lang.textDirection,
      child: ModelDescendant<IDataContext>(
        onUpdate: (context, _, data) {
          if (data.users.isNotEmpty)
            _userName.text = data.users.first.name ?? "";

          return Scaffold(
            appBar: AppBar(
              title: Text(lang.strings.welcome, style: TextStyle(fontFamily: lang.titleFontName),),
              centerTitle: true,
              actions: <Widget>[
                IconButton(
                  icon: Icon(Icons.language),
                  onPressed: (){},
                )
              ],
            ),
            body: Column(
              children: <Widget>[
                Expanded(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      CircleAvatar(
                        radius: 60.0,
                        backgroundImage: AssetImage("assets/pictures/boy.png"),
                        backgroundColor: Theme.of(context).primaryColor,
                      ),
                      SizedBox(height: 15.0,),
                      SizedBox(
                        child: TextField(decoration: InputDecoration(hintText: lang.strings.userName, prefixIcon: Icon(Icons.people_outline)), controller: _userName,),
                        width: 250.0,
                      ),
                      SizedBox(
                        child: TextField(decoration: InputDecoration(hintText: lang.strings.password, prefixIcon: Icon(Icons.lock)), obscureText: true, controller: _userPassword,),
                        width: 250.0,
                      ),
                      SizedBox(height: 15.0,),
                      RaisedButton(
                        child: Text(lang.strings.signIn, style: TextStyle(color: Colors.white),),
                        onPressed: () async {
                          if (data.users.isEmpty) {
                            if (_userName.text.length < 1 || _userPassword.text.length < 6){
                              await showMessageDialog(context: context, content: "ئەزالىق نامىڭىز قۇرۇق بولسا ۋە پارولىڭىز 6 خانىدىن كەم بولسا بولمايدۇ");
                              return;
                            }
                            data.users.add(new User()
                              ..name = _userName.text
                              ..password = _userPassword.text
                            );
                          }
                          var user = data.users.firstWhere((user) => user.name == _userName.text && user.password == _userPassword.text, orElse: () => null);

                          if (user == null){
                            await showMessageDialog(context: context, content: "ئەزالىق نامىڭىز ياكى پارولىڭىز خاتا");
                            return;
                          }
                          data.currentUser = user;
                          Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (context) => MainPage()));

                        },
                        color: Theme.of(context).primaryColor,
                        shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(8.0)
                        ),
                      ),
                      Text(lang.strings.or, style: TextStyle(color: Theme.of(context).primaryColor, fontStyle: FontStyle.italic),),
                      SizedBox(height: 5.0,),
                      Text(lang.strings.forgetPassword, style: TextStyle(color: Theme.of(context).primaryColor),),
                    ],
                  ),
                ),
                Container(
                  color: Theme.of(context).primaryColor,
                  child: Text(lang.strings.companyName, style: TextStyle(color: Colors.white), textAlign: TextAlign.center,),
                  width: double.infinity,
                  padding: EdgeInsets.symmetric(vertical: 8.0),
                ),
              ],
            ),
          );
        },
      ),
    );
  }
}

